package com.example.bbs.web.servlet;
/**
 * @auther: zhangxin
 * @Description:
 */

import com.example.bbs.model.User;
import com.example.bbs.service.UserService;
import com.example.bbs.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/doLogin")
public class LoginServlet extends HttpServlet {


     private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html;charset=utf8");
        req.setCharacterEncoding("UTF-8");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");

        User user = new User(userName,userPassword);
        user = userService.doLogin(user);

        if(user == null){
              req.setAttribute("fail","用户名或密码错误");
              req.getRequestDispatcher("login.jsp").forward(req,res);
        }else{
            HttpSession session = req.getSession();
            session.setAttribute("loginUser", user);
            Cookie cookie = new Cookie("loginUser", user.getUserName());
            cookie.setMaxAge(60 * 5);
            res.addCookie(cookie);
            userService.updateLoginTime(user.getUserId());
            res.sendRedirect("/boards.jsp");
        }
    }
}
